package com.own.business.system.user.business.core;

import com.own.business.system.user.business.hook.SystemUserInfoUpdatePhoneHook;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * SystemUserInfoUpdatePhoneSpringHook
 *
 * @author chenxueli
 * @date 2023-07-01 16:28:00
 */
@Slf4j
@Component
@SuppressWarnings("all")
public class SystemUserInfoUpdatePhoneSpringHook implements ApplicationContextAware, ApplicationListener<ApplicationEvent> {

    private static final List<SystemUserInfoUpdatePhoneHook> UPDATE_PHONE_HOOK_LIST = new ArrayList<>();
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        applicationContext = context;
    }

    /**
     * 更新手机号之前的回调
     *
     * @param userId   用户id
     * @param oldPhone 旧手机号
     * @param newPhone 新手机号
     */
    public void before(Long userId, String oldPhone, String newPhone) {
        UPDATE_PHONE_HOOK_LIST.forEach(hook -> hook.before(userId, oldPhone, newPhone));
    }

    /**
     * 更新手机号之后的回调
     *
     * @param userId   用户id
     * @param oldPhone 旧手机号
     * @param newPhone 新手机号
     */
    public void after(Long userId, String oldPhone, String newPhone) {
        UPDATE_PHONE_HOOK_LIST.forEach(hook -> hook.after(userId, oldPhone, newPhone));
    }

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if (event instanceof ApplicationReadyEvent) {
            applicationContext.getBeansOfType(SystemUserInfoUpdatePhoneHook.class).forEach((key, hook) -> {
                UPDATE_PHONE_HOOK_LIST.add(hook);
                log.debug("修改手机号钩子===>【{}】完成注册", key);
            });
        }
    }

}
